package cn.fl.finance.controller;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.capital.condition.CapPayInfoQueryCondition;
import cn.fl.capital.constant.CapitalConstant;
import cn.fl.capital.service.ICapPayInfoService;
import cn.fl.capital.vo.CapPayInfoVO;
import cn.fl.finance.api.IFinLoanDtlApiService;
import cn.fl.finance.api.IFinPayDtlApiService;
import cn.fl.finance.condition.FinPayDtlRQC;
import cn.fl.finance.constant.FinLoanConstant;
import cn.fl.finance.dto.FinPayDtlDTO;
import cn.fl.finance.service.IFinLoanDtlService;
import cn.fl.finance.service.IFinPayDtlRService;
import cn.fl.finance.vo.AssetBindVO;
import cn.fl.finance.vo.FinLoanDtlVO;
import cn.fl.finance.vo.FinPayDtlRVO;
import cn.fl.system.service.ISysDictionaryService;
import com.alibaba.fastjson.JSON;
import freemarker.template.utility.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import sun.rmi.runtime.Log;

import java.util.*;

/**
 * 借款申请-资产绑定
 * 作者:hongyanbo
 * 时间:2018/10/11
 */
@Controller
@RequestMapping("/capital/finance/loan/apply/asset")
public class FinLoanApplyAssetBindController {

    @Autowired
    private ICapPayInfoService capPayInfoService;
    @Autowired
    private IFinPayDtlRService finPayDtlRService;
    @Autowired
    private IFinPayDtlApiService finPayDtlApiService;
    @Autowired
    private IFinLoanDtlService finLoanDtlService;
    @Autowired
    private ISysDictionaryApiService sysDictionaryService;

    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;
    /**
     * 绑定资产页面
     * @param model
     * @param payDtlId
     * @param editAble 0:不可编辑 1：可以编辑
     * @param payAmt 本次申请付款金额（元）
     * @return
     */
    @RequestMapping("/toBindList.do")
    public ModelAndView toBindList(ModelAndView model,String payDtlId,@RequestParam(required=false,defaultValue = "1") String editAble,Double payAmt){
        FinPayDtlDTO byId = this.finPayDtlApiService.getById(Long.valueOf(payDtlId));
        if(byId!=null){
            model.addObject("payAmt",payAmt);
            FinLoanDtlVO dtlVO = finLoanDtlService.selectById(byId.getLoanDtlId());
            model.addObject("loanTypCdNm",dtlVO.getLoanTypCdNm());
        }
        model.setViewName("finance/loan/apply/asset/assetBindList");
        model.addObject("payDtlId",payDtlId);
        model.addObject("editAble",editAble);
        // 查询绑定资产数目  finPayDtlRListSize
        int size = 0;
        if(StringUtils.isNotBlank(payDtlId)){
            FinPayDtlRQC qc = new FinPayDtlRQC();
            qc.setPayDtlId(Long.valueOf(payDtlId));
            List<FinPayDtlRVO> finPayDtlRList = this.finPayDtlRService.selectList(qc);
            if(CollectionUtils.isNotEmpty(finPayDtlRList)){
                size = finPayDtlRList.size();
            }
        }
        model.addObject("finPayDtlRListSize",size);
        // 所属区域
        List<SysDictionaryDTO> regionList = sysDictionaryApiService.searchGroup(FinLoanConstant.SYS_CD, FinLoanConstant.ORG_CD, FinLoanConstant.CODE_REGION_CD);
        model.addObject("regionList", regionList);
        return model;
    }

    /**
     *
     * @param payDtlId
     * @return
     */
    @RequestMapping("initBindList.do")
    @ResponseBody
    public ListPageVO initBindList(Long payDtlId){
        // 初始化
        FinPayDtlRQC qc = new FinPayDtlRQC();
        qc.setPayDtlId(payDtlId);
        List<FinPayDtlRVO> finPayDtlRVOS = this.finPayDtlRService.selectList(qc);
        List<Long> paySchIdList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(finPayDtlRVOS)){
            for (FinPayDtlRVO finPayDtlRVO : finPayDtlRVOS) {
                paySchIdList.add(finPayDtlRVO.getPaySchId());
            }
            // 查询CapPayInfoVO
            CapPayInfoQueryCondition qc2 = new CapPayInfoQueryCondition();
            Pager pager = new Pager();
            pager.setCondition(qc2);
            pager.setCurrentPage(1);
            pager.setEveryPage(100);
            List<String> payStsCdList = new ArrayList<>();
            payStsCdList.add(CapitalConstant.CODE_CAP_PAY_STS_CD_3);
            payStsCdList.add(CapitalConstant.CODE_CAP_PAY_STS_CD_5);
            qc2.setPayStsCdList(payStsCdList);
            qc2.setPaySchIdList(paySchIdList);
            pager = this.capPayInfoService.searchListPage(pager);
            List<CapPayInfoVO> capPayInfoVOList = (List<CapPayInfoVO>) pager.getResultList();
            Map<Long,CapPayInfoVO> map = new HashMap<>();
            if(CollectionUtils.isNotEmpty(capPayInfoVOList)){
                for (CapPayInfoVO capPayInfoVO : capPayInfoVOList) {
                    map.put(capPayInfoVO.getPaySchId(),capPayInfoVO);
                }
            }
            // 拼装结果 AssetBindVO
            List<AssetBindVO> resultList = new ArrayList<>();
            for (FinPayDtlRVO finPayDtlRVO : finPayDtlRVOS) {
                AssetBindVO vo = new AssetBindVO();
                vo.setId(finPayDtlRVO.getId());
                vo.setPayAmt(DecimalUtils.convertFenToYuan(finPayDtlRVO.getPayAmt()));
                vo.setRem(finPayDtlRVO.getRem());
                CapPayInfoVO capPayInfoVO = map.get(finPayDtlRVO.getPaySchId());
                if(capPayInfoVO!=null){
                    vo.setPaySchId(capPayInfoVO.getPaySchId());
                    vo.setCstNm(capPayInfoVO.getCstNm());
                    vo.setContNo(capPayInfoVO.getContNo());
                    vo.setPaySchNo(capPayInfoVO.getPaySchNo());
                    vo.setBuOrgCdNm(capPayInfoVO.getBuOrgCdNm());
                    vo.setPrOrgCdNm(capPayInfoVO.getPrOrgCdNm());
                    vo.setCyOrgCdNm(capPayInfoVO.getCyOrgCdNm());
                    vo.setCstMgrNm(capPayInfoVO.getCstMgrNm());
                    vo.setCstMgrRgnCdNm(capPayInfoVO.getCstMgrRgnCdNm());
                }
                resultList.add(vo);
            }
            return new ListPageVO(resultList,resultList.size());
        }
        return null;
    }

    /**
     * 到资产列表页面
     * 资产查询和选择的页面
     * @return
     */
    @RequestMapping("/toListPage.do")
    public ModelAndView toListPage(ModelAndView model){
        model.setViewName("finance/loan/apply/asset/assetListPage");
        return model;
    }

    /**
     * 初始化资产列表
     * @param qc
     * @param page
     * @param pagesize
     * @return
     */
    @RequestMapping("/initList.do")
    @ResponseBody
    public ListPageVO initList(CapPayInfoQueryCondition qc,int page,int pagesize){
        Pager pager = new Pager();
        pager.setCondition(qc);
        pager.setCurrentPage(page);
        pager.setEveryPage(pagesize);
        List<String> payStsCdList = new ArrayList<>();
        payStsCdList.add(CapitalConstant.CODE_CAP_PAY_STS_CD_3);
        payStsCdList.add(CapitalConstant.CODE_CAP_PAY_STS_CD_5);
        qc.setPayStsCdList(payStsCdList);
        List<String> prdStsList = new ArrayList<>();
        List<KeyValueVO> dicList = this.sysDictionaryService.getKvList("FIN11000", "11000", "0000");
        for (KeyValueVO vo : dicList) {
            prdStsList.add(vo.getKey());
        }
        qc.setPrdStsCdList(prdStsList);
        pager = this.capPayInfoService.searchListPage(pager);


        ListPageVO res = new ListPageVO(pager.getResultList(),pager.getTotalCount());
        return res;
    }

    /**
     * 保存资产绑定
     * @return
     */
    @RequestMapping("doSave.do")
    @ResponseBody
    public DataResultVO doSave(String data,@RequestParam Long payDtlId,Double payAmt){
        DataResultVO res = null;
        try{
            res  =this.finPayDtlRService.saveAssetBind(data,payDtlId,payAmt);
        }catch (BaseException e){
            res = new DataResultVO(0,e.getMessage());
        }catch (Exception e){
            BaseLogUtils.newLogger("未知错误").setThrowable(e).error(LogExceptionEnum.API_CODE_0101);
        }
        return res;
    }
    @RequestMapping("delete.do")
    @ResponseBody
    public void delete(String data) {
        List<String> idList = JSON.parseArray(data, String.class);
        if (CollectionUtils.isEmpty(idList)) {
            return;
        }
        this.finPayDtlRService.deleteByIdList(idList);
    }
}
